<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>联大商城</title>
    <link rel="stylesheet" href="../plugins/element-ui/index.css">
    <script src="../plugins/vue/vue.js"></script>
    <script src="../plugins/element-ui/index.js"></script>
    <script src="../plugins/axios/axios.min.js"></script>
    <script src="../plugins/request.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        .container {
            display: flex;
            margin: 20px;
        }

        .sidebar {
            width: 250px;
            background-color: #fff;
            padding: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .content {
            flex: 1;
            padding: 20px;
            background-color: #fff;
            margin-left: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .category-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: #fafafa;
        }

        .category-info {
            display: flex;
            align-items: center;
        }
        .order-info {
            display: flex;
            align-items: center;
        }
        .order-item {
            flex: 1 1 200px;
            margin: 10px;
        }
        .order-items {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 10px;
        }

        .category-info img {
            margin-right: 10px;
            border-radius: 5px;
        }

        .purchase-section {
            display: flex;
            align-items: center;
        }

        .purchase-section button {
            margin: 0 5px;
            padding: 5px 10px;
            border: none;
            border-radius: 3px;
            background-color: #409EFF;
            color: #fff;
            cursor: pointer;
        }

        .purchase-section button:hover {
            background-color: #66b1ff;
        }

        .purchase-section span {
            margin: 0 10px;
            font-size: 16px;
        }

        .global-button {
            position: fixed;
            top: 10px;
            right: 10px;
            display: flex;
            align-items: center;
            cursor: pointer;
        }
        .user-item {
            background-color: #f9f9f9;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
        .beijing {
            background-color: #c6e2ff;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border: 1px solid #ddd;
        }
        .erji{
            background-color: #c6e2ff;
        }


        .global-button img {
            margin-right: 5px;
        }
        .order-image {
            width: 100px;
            margin-right: 20px;
        }
        .order-details {
            display: flex;
            flex-direction: column;
            flex: 1;
        }
        .order-group h4 {
            margin-bottom: 10px;
            color: #333;
        }
        .order-group {
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
            background-color: #e0f7fa;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body>
<h1 style="text-align: center; margin-top: 20px;">商城</h1>

<div id="app" class="container">
    <div class="sidebar">
        <el-menu :default-active="activeMenu" class="el-menu-vertical-demo" @select="handleSelect">
            <el-menu-item index="1" class="beijing">新闻公告</el-menu-item>
            <el-submenu index="2" class="beijing">
                <template slot="title">商品</template>
                <el-menu-item index="2-0" class="erji">全部</el-menu-item>
                <el-menu-item index="2-1" class="erji">电子产品</el-menu-item>
                <el-menu-item index="2-2" class="erji">零食</el-menu-item>
                <el-menu-item index="2-3" class="erji">日常用品</el-menu-item>
            </el-submenu>
            <el-menu-item index="3" class="beijing">我的信息</el-menu-item>
            <el-menu-item index="4" class="beijing">我的订单</el-menu-item>
        </el-menu>
    </div>
    <div class="content">
        <!--        <h2 v-if="activeMenu === '1'">新闻公告</h2>-->
        <h2 v-if="activeMenu === '3'">信息</h2>
        <h2 v-if="activeMenu === '4'">订单</h2>

        <div v-if="activeMenu === '3' && userInfo">
            用户名
            <el-input v-model="userInfo.username" placeholder="Enter your username"></el-input>
            密码
            <el-input v-model="userInfo.password" placeholder="Enter your email"></el-input>
            电话
            <el-input v-model="userInfo.phone" placeholder="Enter your phone number"></el-input>
            地址
            <el-input v-model="userInfo.email" placeholder="Enter your address"></el-input>
            <el-button type="primary" @click="updateUserInfo">修改</el-button>
        </div>
        <div v-if="activeMenu === '4' && orders.length > 0">
            <h3>我的订单</h3>
            <div v-for="order in orders" :key="order.id" class="order-group">
                <h4>订单号: {{ order.id }}</h4>
                <div class="order-items">
                    <div v-for="detail in order.details" :key="detail.id" class="order-item">
                        <div class="order-info">
                            <img :src="detail.image" alt="detail.name" class="order-image">
                            <div class="order-details">
                                <h3>{{ detail.name }}</h3>
                                <p>数量: {{ detail.num }}</p>
                                <p>价格: {{ detail.price }}</p>
                            </div>
                        </div>
                    </div>
                </div>
                <p>总价: {{ order.fprice }}</p>
            </div>
            <el-pagination
                    @current-change="handlePageChange"
                    :current-page="currentPage"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="totalOrders">
            </el-pagination>
        </div>
        <div v-if="activeMenu === '1'">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <h2>新闻公告</h2>

            </div>
            <div v-if="news && news.length">
                <div v-for="item in news" :key="item.id">
                    <h3 @click="showNewsDetails(item)">{{ item.title }} - {{ item.date }}</h3>
                </div>
            </div>
        </div>

        <el-dialog :visible.sync="showDetailsModal" title="新闻详情">
            <h3>{{ selectedNews.title }}</h3>
            <p>{{ selectedNews.content }}</p>
            <p>{{ selectedNews.date }}</p>
            <span slot="footer" class="dialog-footer">
        <el-button @click="showDetailsModal = false">关闭</el-button>
    </span>
        </el-dialog>



        <h2 v-if="activeMenu !== '1' && activeMenu !== '3' && activeMenu !== '4'">商品信息</h2>
        <div v-if="activeMenu !== '1' && activeMenu !== '3' && activeMenu !== '4'" v-for="category in categories" :key="category.id"
             class="category-item">
            <div class="category-info">
                <img :src="category.image" alt="category.name" width="100">
                <h3>{{ category.name }}</h3>
            </div>
            <div class="purchase-section">
                <button v-if="category.num === 0" @click="addToCart(category)">加入购物车</button>
                <div v-else>
                    <button @click="decreaseQuantity(category)">-</button>
                    <span>{{ category.num }}</span>
                    <button @click="increaseQuantity(category)">+</button>
                </div>
            </div>
        </div>
    </div>

    <el-dialog :visible.sync="cartModalVisible" title="购物车">
        <div v-if="selectedCategory">
            <h3>{{ selectedCategory.name }}</h3>
            <img :src="selectedCategory.image" alt="selectedCategory.name" width="100">
            <div class="purchase-section">
                <button @click="decreaseQuantity(selectedCategory)">-</button>
                <span>{{ selectedCategory.num }}</span>
                <button @click="increaseQuantity(selectedCategory)">+</button>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cartModalVisible = false">取消</el-button>
            <el-button type="primary" @click="addToCart(selectedCategory)">确定</el-button>
        </span>
    </el-dialog>

    <el-button v-if="cartNotEmpty" type="primary" @click="showCartModal = true; fetchShopingCar()">查看购物车
    </el-button>
    <el-dialog :visible.sync="showCartModal" title="购物车详情">
        <div v-for="item in shopingCar" :key="item.id" class="category-item">
            <div class="category-info">
                <img :src="item.image" alt="item.name" width="100">
                <h3>{{ item.name }}</h3>
            </div>
            <div class="purchase-section">
                <button @click="decreaseQuantity(item)">-</button>
                <span>{{ item.num }}</span>
                <button @click="increaseQuantity(item)">+</button>
            </div>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="showCartModal = false">继续购物</el-button>
            <el-button type="primary" @click="redirectToPay">去支付</el-button>
        </span>
    </el-dialog>

    <div class="global-button" @click="redirectToMyInfo"
         style="background-color: #e0f7fa; border-radius: 15px; padding: 10px;">
        <img src="../image/123.png" alt="My Info" width="20">
        <span style="font-size: 16px; color: #409EFF;">我的</span>
    </div>
    <div class="global-button" @click="logout"
         style="background-color: #e0f7fa; border-radius: 15px; padding: 10px; margin-left: 10px;">
        <span style="font-size: 16px; color: #409EFF;">登出</span>
    </div>

</div>

<script>
    new Vue({
        el: '#app',
        data: {
            activeMenu: '1',
            categories: [],
            news: [],
            cartModalVisible: false,
            selectedCategory: null,
            shopingCar: [],
            showCartModal: false,
            cartNotEmpty: false,
            userInfo: {},
            username: '',
            orders: [],
            showPublishModal: false,
            newNewsTitle: '',
            newNewsContent: '',
            showDetailsModal: false, // New data property for details modal visibility
            selectedNews: {}
        },
        mounted() {
            this.fetchNews();
            this.fetchShopingCar();
            this.username = localStorage.getItem('username') || this.getQueryParam('username');
        },
        methods: {
            fetchCategories(categoryId) {
                let url = '/categories/' + categoryId;
                axios.get(url)
                    .then(response => {
                        this.categories = response.data.map(category => {
                            const cartItem = this.shopingCar.find(item => item.id === category.id);
                            return {
                                ...category,
                                num: cartItem ? cartItem.num : category.num,
                                inCart: !!cartItem
                            };
                        });
                        console.log(this.categories);
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            confirmCart() {
                axios.get('/categories/list')
                    .then(response => {
                        console.log('Categories list:', response.data);
                        this.categories = response.data.map(category => {
                            const cartItem = this.shopingCar.find(item => item.id === category.id);
                            return {
                                ...category,
                                num: cartItem ? cartItem.num : category.num,
                                inCart: !!cartItem
                            };
                        });
                        this.showCartModal = false;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            handleSelect(key, keyPath) {
                console.log(key, keyPath);
                this.activeMenu = key;
                if (key === '1') {
                    this.fetchNews();
                } else if (key === '2-0') {
                    this.fetchCategories('list');
                } else if (key === '2-1') {
                    this.fetchCategories('1');
                } else if (key === '2-2') {
                    this.fetchCategories('2');
                } else if (key === '2-3') {
                    this.fetchCategories('3');
                } else if (key === '3') {
                    this.fetchUserInfo();
                } else if (key === '4') {
                    this.fetchOrders();
                }
            },
            fetchUserInfo() {
                axios.get('/user/select')
                    .then(response => {
                        console.log('User info:', response.data);
                        this.userInfo = response.data;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            updateUserInfo() {
                axios.post('/user/update', this.userInfo)
                    .then(response => {
                        console.log('User info updated:', response.data);
                        alert('User info updated successfully');
                    })
                    .catch(error => {
                        console.error(error);
                        alert('失败');
                    });
            },

            fetchNews() {
                axios.get('/news/getnews')
                    .then(response => {
                        if (response.data === 'NOTLOGIN') {
                            window.location.href = '/front/login.html';
                        } else {
                            this.news = response.data; // Assign the response data to news
                            console.log(this.news);
                        }
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            fetchShopingCar() {
                axios.get('/categories/getShopingCar')
                    .then(response => {
                        console.log('Shoping car:', response.data);
                        this.shopingCar = response.data.map(item => ({
                            ...item,
                            num: item.num
                        }));
                        this.cartNotEmpty = this.shopingCar.length > 0;
                        this.updateCategoriesWithCart();
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            openCartModal(category) {
                this.selectedCategory = { ...category, num: category.num || 1 };
                this.cartModalVisible = true;
            },
            addToCart(category) {
                category.inCart = true;
                category.num = 1;
                this.cartNotEmpty = true;
                this.cartModalVisible = false;

                axios.post('/categories/add', {
                    ...category,
                    num: category.num
                })
                    .then(response => {
                        console.log('Added to cart:', response.data);
                        this.fetchShopingCar();
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            increaseQuantity(category) {
                category.num++;
                axios.post('/categories/add', {
                    ...category,
                    num: category.num
                })
                    .then(response => {
                        console.log('Increased quantity:', response.data);
                        this.fetchShopingCar();
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            updateCategoriesWithCart() {
                this.categories = this.categories.map(category => {
                    const cartItem = this.shopingCar.find(item => item.id === category.id);
                    return {
                        ...category,
                        num: cartItem ? cartItem.num : category.num,
                        inCart: !!cartItem
                    };
                });
            },
            decreaseQuantity(category) {
                if (category.num > 1) {
                    category.num--;
                    axios.post('/categories/jian', {
                        ...category,
                        num: category.num
                    })
                        .then(response => {
                            console.log('Decreased quantity:', response.data);
                            this.fetchShopingCar();
                        })
                        .catch(error => {
                            console.error(error);
                        });
                } else {
                    category.num = 0;
                    category.inCart = false;
                    axios.post('/categories/jian', {
                        ...category,
                        num: 0
                    })
                        .then(response => {
                            console.log('Removed from cart:', response.data);
                            this.cartNotEmpty = this.shopingCar.length > 0;
                            this.fetchShopingCar();
                        })
                        .catch(error => {
                            console.error(error);
                        });
                }
            },
            redirectToPay() {
                window.location.href = '/front/pay.html';
            },
            redirectToMyInfo() {
                this.activeMenu = '3';
                this.fetchUserInfo();
            },
            getQueryParam(param) {
                const urlParams = new URLSearchParams(window.location.search);
                return urlParams.get(param);
            },
            logout() {
                axios.get('/user/logout')
                    .then(response => {
                        this.$notify({
                            title: 'Success',
                            message: '登出成功',
                            type: 'success'
                        });
                        setTimeout(() => {
                            window.location.href = '/front/login.html';
                        }, 1000);
                    })
                    .catch(error => {
                        this.$notify({
                            type: 'error',
                            title: 'Error',
                            message: '登出失败'
                        });
                        console.error(error);
                    });
            },
            fetchOrders(pageNum = 1, pageSize = 10) {
                axios.get('/pay/get', {
                    params: {
                        pageNum: pageNum,
                        pageSize: pageSize
                    }
                })
                    .then(response => {
                        console.log('Orders:', response.data);
                        this.orders = response.data.records;
                        this.totalOrders = response.data.total;
                        this.currentPage = pageNum;
                    })
                    .catch(error => {
                        console.error(error);
                    });
            },
            handlePageChange(page) {
                this.fetchOrders(page, this.pageSize);
            },
            data() {
                return {
                    orders: [],
                    totalOrders: 0,
                    currentPage: 1,
                    pageSize: 10
                };
            },
            publishNews() {
                axios.post('/news/publish', {
                    title: this.newNewsTitle,
                    content: this.newNewsContent
                })
                    .then(response => {
                        console.log('News published:', response.data);
                        alert('新闻公告发布成功');
                        this.fetchNews(); // 重新获取新闻公告
                        this.showPublishModal = false; // 关闭弹窗
                        this.newNewsTitle = ''; // 清空表单
                        this.newNewsContent = '';
                    })
                    .catch(error => {
                        console.error(error);
                        alert('发布失败');
                    });
            },
            showNewsDetails(news) {
                this.selectedNews = news;
                this.showDetailsModal = true;
            },

        }
    });
</script>
</body>
</html>